import { ref } from 'vue'
import { defineStore } from 'pinia'
import api from '@/api/banner'
import type { BannerItem } from '@/config/types'
import type { BannerForm } from '@/config/forms'

export const useBannerStore = defineStore('banner', () => {
  const loading = ref<boolean>(false)
  const banners = ref<BannerItem[]>([])

  const updating = ref<boolean>(false)
  const banner = ref<BannerItem | null>(null)

  async function loadBanners() {
    loading.value = true
    try {
      const res = await api.getList()
      banners.value = res.data
      loading.value = false
    } catch (e) {
      loading.value = false
    }
  }

  async function loadBanner(id: number) {
    updating.value = true
    try {
      const res = await api.getItem(id)
      banner.value = res.data
      updating.value = false
    } catch (e) {
      updating.value = false
    }
  }

  async function deleteBanner(id: number) {
    loading.value = true
    try {
      const res = await api.delete(id)
      updating.value = false
      return res.data
    } catch (e) {
      updating.value = false
    }
    return false
  }

  async function saveBanner() {
    updating.value = true
    let result = false
    try {
      let res
      if (banner.value) {
        const form: BannerForm = {
          title: banner.value.title,
          cover: banner.value.cover,
          link: banner.value.link,
          onself: banner.value.onself
        }
        if (banner.value.id > 0) {
          res = await api.update(banner.value.id, form)
        } else {
          res = await api.create(form)
        }
        result = res.data
      }
      updating.value = false
    } catch (e) {
      updating.value = false
    }
    return result
  }

  function newBanner() {
    banner.value = {
      id: 0,
      title: '',
      cover: '',
      link: '#',
      onself: false,
      updatedAt: 0
    }
  }

  async function updateOnself(val: boolean) {
    const ids = banners.value.filter((item) => item.onself === val).map((item) => item.id)
    await api.onself(ids, val)
  }

  return {
    loading,
    banners,
    loadBanners,
    deleteBanner,
    updateOnself,

    updating,
    banner,
    loadBanner,
    newBanner,
    saveBanner
  }
})
